package sample;

import javafx.beans.value.ChangeListener;
import javafx.collections.*;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * JavaFX 集合的练习
 */
public class Main2 {

    //如何使用ObservableList，ObservableMap和FXCollections
    @Test
    public void test1(){
        List<String> list = new ArrayList<>();

        ObservableList<String> observableList = FXCollections.observableList(list);

        list.add("item one");
        observableList.add("item two");

        //操作修改针对于在添加监听器后的添加操作
        observableList.addListener(new ListChangeListener<String>() {
            @Override
            public void onChanged(ListChangeListener.Change change) {
                System.out.println("有操作修改 : " + change);
            }
        });

       /* observableList.addListener(new ListChangeListener<String>() {
            @Override
            public void onChanged(Change<? extends String> c) {
                System.out.println("有操作修改");
            }
        });*/

        list.add("haha");
        observableList.add("xixi");

        System.out.println("Size : " + observableList.size());
    }

    //监听ObservableMap上的更改。
    @Test
    public void test2(){

        Map<String,String> map = new HashMap<String , String>();

        ObservableMap<String,String> observableMap = FXCollections.observableMap(map);

        observableMap.addListener(new MapChangeListener<String, String>() {
            @Override
            public void onChanged(Change<? extends String, ? extends String> change) {
                System.out.println("修改记录 ：" + change);
            }
        });

        map.put("姓名" ,"Tom");
        observableMap.put("年龄" ,"23");//这个put映射到map中
        System.out.println("Size:" + observableMap.size());

    }

    @Test
    public void test3(){
        List<String> list = new ArrayList<String>();

        list.add("nihao");

        ObservableList<String> observableList = FXCollections.observableList(list);

        observableList.addListener(new ListChangeListener<String>() {
            @Override
            public void onChanged(ListChangeListener.Change c) {

                while (c.next()){

                    System.out.println("添加了：" + c.wasAdded());

                    System.out.println("替换:" + c.wasReplaced());

                    System.out.println("移除了：" + c.wasRemoved());

                    System.out.println("改变次序" + c.wasPermutated());
                    System.out.println("-----------------------------");
                }
            }
        });
        observableList.remove(0);
        observableList.add("buhao");
    }

}
